package ru.brostudios.cosmicdonutlivewallpapers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;

public class Star {

	private int width, height;
	private Texture texture;
	private FloatBuffer floatBuffer;
	private float scale;
	private int x, y;
	private float alpha;
	
	public Star(Texture texture, int screenWidth, int screenHeight, float scale) {
		this.texture = texture;
		this.width = screenWidth;
		this.height = screenHeight;
		this.scale = scale;
		floatBuffer = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
		floatBuffer.put(new float[] {
			-texture.width/2.0f, +texture.height/2.0f, 0.0f, 0.0f,
			-texture.width/2.0f, -texture.height/2.0f, 0.0f, 1.0f,
			+texture.width/2.0f, +texture.height/2.0f, 1.0f, 0.0f,
			+texture.width/2.0f, -texture.height/2.0f, 1.0f, 1.0f
		});
		Random rnd = new Random();
		x = rnd.nextInt(width)-width/2;
		y = rnd.nextInt(height)-height/2;
		alpha = rnd.nextFloat();
	}
	
	public void Draw(GL10 gl) {
		gl.glColor4f(1.0f, 1.0f, 1.0f, alpha);
		gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		floatBuffer.position(0);
		gl.glVertexPointer(2, GL10.GL_FLOAT, 4*4, floatBuffer);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		floatBuffer.position(2);
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 4*4, floatBuffer);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glPushMatrix();
		gl.glLoadIdentity();
		gl.glTranslatef(x, y, 0);
		gl.glScalef(scale, scale, 1.0f);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, texture.glid);
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
		gl.glPopMatrix();
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisable(GL10.GL_BLEND);
		gl.glDisable(GL10.GL_TEXTURE_2D);
		gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	}
	
	public void Update() {
		alpha += 0.02f;
		if(alpha > 1.0) {
			alpha = 0;
			Random rnd = new Random();
			x = rnd.nextInt(width)-width/2;
			y = rnd.nextInt(height)-height/2;
		}
	}
	
}